package com.example.qyweixin.service;

import com.example.qyweixin.config.RequestConfig;
import com.example.qyweixin.constants.Constants;
import com.example.qyweixin.dao.UserDao;
import com.example.qyweixin.dto.User;
import com.example.qyweixin.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.logging.Logger;


/**
 * 通讯录管理
 */
@Service
public class UserService {

    @Resource
    RequestConfig config;

    @Resource
    UserDao userDao;

    /**
     * 获取驱动测试用例数据
     * @return
     */
    public List<User> getUserData(){
        List<User> userList = userDao.findUserList();
        return userList;
    }

    /**
     * 获取token
     * @return
     */
    @PostConstruct
    private String getUserToken()  {

        String token = "";
        //1、获取token地址
        StringBuilder sb = new StringBuilder();
        String tokenUrl = sb.append(config.getBaseUrl()).append(config.getTokenUri())
                .append("?corpid=").append(config.getCorpid())
                .append("&corpsecret=").append(config.getUserInfos().get("corpsecret")).toString();
        //2、发送请求获取token
        String res = HttpClientUtil.getResponse(tokenUrl);
        try {
            JSONObject jsonObject = new JSONObject(res);
            if((int)jsonObject.get("errcode")==0){
                //3、获取token
                token = (String) jsonObject.get("access_token");
                Constants.tokenMap.put("token",token);
            }else{
                Logger.getLogger("获取token失败", (String) jsonObject.get("errmsg"));
            }
        }catch (JSONException e){
            e.printStackTrace();
        }

        return token;
    }



}
